<template>
    <div class="device-list" v-loading="showLoading" style="height: -webkit-fill-available">
        <div style="margin-top: -20px;padding-bottom: 10px;">
            <ul class="global-operation-list" style="margin-top: 20px;">
                <li class="global-operation-left">
                    <ul class="global-filter-list">
                        <!-- <li class="global-filter-item">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="chooseAllProject()">选择项目</el-button>
                        </li> -->
                        <li class="global-filter-item"
                            v-if="showButtonType == 1 && !($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55)))">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="changeShowButton(2)">查询</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="showButtonType == 2 && !($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="changeShowButton(1)">取消查询</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="showButtonType == 1 && !($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="changeShowButton(3)">排期</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="showButtonType == 3 && !($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="changeShowButton(1)">取消排期</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="!($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="addOtherMediumProject()">新增其他项目</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="!($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="handleExportTableShow(1)">表格导出</el-button>
                        </li>
                        <li class="global-filter-item"
                            v-if="!($store.state.userInfo.role && ($store.state.userInfo.role.includes(40) || $store.state.userInfo.role.includes(55))) ">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="handleExportTableShow(2)">统计导出</el-button>
                        </li>

                        <li class="global-filter-item">
                            <el-button type="primary" class="global-filter-item-search"
                                :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                @click="handchoosemouth"> {{ islocalTime ? formatterTime(islocalTime) : '选择月份'
                                }}</el-button>
                        </li>

                        <el-tooltip class="tool-msg" effect="dark" :visible-arrow="false" content="按住shift+滚轮即可上下滚动"
                            placement="bottom">
                            <i class="el-icon-question primary-color"></i>
                        </el-tooltip>

                        <div class="choose_project_list">
                            <div class="project_list">
                                <div class="project_item"
                                    v-if="chooseAllProjectShowList && chooseAllProjectShowList.length > 0">
                                    <div class="project_item_title">
                                        {{ chooseAllProjectShowList[0].projectType == 1 ? "易货" : "媒体-其他" }}项目：
                                    </div>
                                    <div class="project_item_content">
                                        <div class="project_item_content_list"
                                            v-for="(item, index) in chooseAllProjectShowList" :key="index">
                                            <div class="project_item_content_item">
                                                <el-button-group>
                                                    <el-button size="mini" round
                                                        @click="getOneProjectPackageListMsg(item.id, item.projectType == 1 ? 2 : 3, item.brands)">{{
                                                        item.brands
                                                        }}</el-button>
                                                    <!-- <el-button size="mini" round type="danger" icon="el-icon-delete"
                                                        @click="doDelChooseProject(index, item.projectType == 1 ? 2 : 3)"></el-button> -->
                                                </el-button-group>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div style="margin: -20px 0 0 10px; display: inline-flex;">
                            <div>
                                <el-button type="primary" @click="scrollStartCalendar2"
                                    :disabled="!calendarChooseTime">上个月</el-button>
                            </div>
                            <div v-if="sureTypeShow"
                                style="padding-left: 10px;display: flex;justify-content: center; align-items: center;">
                                <!-- <el-radio :label="1" v-model="sureType">待确定</el-radio>
                                <el-radio :label="2" v-model="sureType">已确定</el-radio> -->
                                <el-radio :label="1" v-model="sureType">审核中</el-radio>
                                <el-radio :label="2" v-model="sureType">暂定</el-radio>
                                <el-radio :label="3" v-model="sureType">未签</el-radio>
                                <el-radio :label="4" v-model="sureType">已签</el-radio>
                                <el-radio :label="5" v-model="sureType">确认</el-radio>
                            </div>
                            <div v-if="sureTypeShow"
                                style="padding-left: 10px;display: flex;justify-content: center; align-items: center;">
                                <!-- <el-input placeholder="请输入天数" v-model="endDayNum" type="Number" :min="1">
                                    <template slot="append">天</template>
                                </el-input> -->
                                <el-input-number v-model="endDayNum" :step="1" :precision="0" :min="1" label="请输入天数">
                                    <template slot="append">天</template>
                                </el-input-number>
                            </div>
                        </div>

                        <div class="colorbiaoshi">
                            <div style="display: flex;align-items: center;margin-bottom: 5px;">
                                <div class="colorbox color1"></div>
                                <div>审核中、暂定、已签</div>
                            </div>

                            <div style="display: flex;align-items: center;margin-bottom: 5px;">
                                <div class="colorbox color2"></div>
                                <div>未签</div>
                            </div>

                            <div style="display: flex;align-items: center;margin-bottom: 5px;">
                                <div class="colorbox color3"></div>
                                <div>确认</div>
                            </div>

                        </div>
                    </ul>
                </li>
            </ul>
        </div>


        <Calendar v-if="dateCalendarDialog" :calendar-show-type="1" :project-choose-map="projectChooseMap"
            :calendar-scroll-left-status="calendarScrollLeftStatus" :data-offline-list="dataPackageOfflineList"
            :calendar-type="calendarType" @scrollEndCalendar="scrollEndCalendar"
            @scrollStartCalendar="scrollStartCalendar" :calendar-start-time="calendarStartTime"
            :calendar-end-time="calendarEndTime" :operationList="operationList" :showButtonType="showButtonType"
            @getOneProjectPackageListMsg="getOneProjectPackageListMsg" :chooseProjectMsg="chooseProjectMsg"
            :sureType="sureType" :showCleanDateType="showCleanDateType" :endDayNum="endDayNum" :projectId="projectId">
        </Calendar>

        <el-dialog title="选择月份" :visible.sync="ischoosemouth" width="50%">
            <el-date-picker v-model="choosemouth" type="month" placeholder="选择月" value-format="yyyy-MM"
                @change="changemouth">
            </el-date-picker>
            <span slot="footer" class="dialog-footer">
                <el-button @click="ischoosemouth = false">取 消</el-button>
                <el-button type="primary" @click="surehandclick">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="chooseProjectTitle" custom-class="otherDialog"
            :visible.sync="chooseMediumOtherProjectDialogVisible" width="50%"
            :before-close="chooseMediumOtherProjectHandleClose" append-to-body>
            <div>
                <div class="device-list">
                    <ul class="global-operation-list" style="margin-top: 20px;">
                        <li class="global-operation-left">
                            <ul class="global-filter-list">
                                <li class="global-filter-item">
                                    <h2 class="global-filter-item-title">关键字：</h2>
                                    <el-input v-model="searchForm.keyword" @change="reProjectPosts"
                                        placeholder="项目名称、品牌" clearable></el-input>
                                </li>
                                <li class="global-filter-item">
                                    <el-button type="primary" class="global-filter-item-search"
                                        :style="{ background: $store.state.theme.theme_color || '#03C192', border: 'none' }"
                                        @click="reProjectPosts()">搜索</el-button>
                                </li>
                            </ul>
                        </li>
                    </ul>
                    <div class="global-table-content">
                        <div class="global-table">
                            <el-table :data="dataList" :header-cell-style="{
        background: '#F6F7FA',
        color: '#333',
        height: '60px',
    }" v-loading="tableLoading" :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" max-height="700" border
                                @selection-change="handleCurrentChangeTable" @select="handleCurrentChangeRow"
                                ref="multipleProjectTable" header-cell-class-name="all-select"
                                v-if="dataList && dataList.length > 0">
                                <el-table-column type="selection" width="55">
                                </el-table-column>
                                <el-table-column prop="projectName" label="项目名称1" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column label="品牌名称" prop="brands" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column label="创建时间" prop="createDate" show-overflow-tooltip>
                                </el-table-column>
                            </el-table>
                            <div class="no-data" v-else
                                style="height: calc(100vh - 130px - 80px);display: flex;align-items: center;justify-content: center;flex-direction: column">
                                <img style="width: 265px;height: 120px;margin-bottom: 32px"
                                    src="@/assets/images/tyNoData.png" alt="" />
                                <div style="font-size: 16px;color: #A5A9B5">暂无数据~</div>
                            </div>
                        </div>
                        <div class="global-page">
                            <div class="global-page-left">
                            </div>
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                :page-sizes="pageSizes" :page-size="pageSize" :current-page="pageNum" background
                                layout="sizes, total, prev, pager, next" :total="total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="chooseMediumOtherProjectHandleClose">取 消</el-button>
                <el-button type="primary" @click="commitChooseMediumProject">确 定</el-button>
            </span>
        </el-dialog>

        <div v-show="projectPackageDrawer" class="show_package">
            <div class="package_msg">
                <div class="package_title">
                    <div class="package_header">
                        <div class="package_header_title">
                            {{ projectPackageDrawerTitle }}
                        </div>
                    </div>
                    <div class="package_header_close" @click="handleCloseProjectPackageDrawer()">
                        <i class="el-icon-close"></i>
                    </div>
                    <div class="package_divider"></div>
                </div>
                <div class="package_content">
                    <div class="package_drawer">
                        <div class="package_drawer_list">
                            <div class="package_drawer_item" v-for="(item, index) in projectPackageList" :key="index">
                                <el-card class="box-card">
                                    <div slot="header" class="clearfix">
                                        <span>{{ item.mediumName }}</span>
                                    </div>
                                    <div v-for="(timeItem, timeIndex) in item.mediumTimeList" :key="timeIndex"
                                        class="text item">
                                        {{ timeItem.chooseDate + ' 至 ' + timeItem.chooseEndDate }}
                                    </div>
                                </el-card>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <el-dialog v-dialogDrags :title="projectPackageDrawerTitle" :visible.sync="projectPackageShow" width="30%"
            :before-close="handleCloseProjectPackageDrawer" :close-on-click-modal="false" :modal-append-to-body="false"
            :modal="false">
            <div class="package_drawer">
                <div class="package_drawer_list">
                    <div class="package_drawer_item" v-for="(item, index) in projectPackageList" :key="index">
                        <el-card class="box-card">
                            <div slot="header" class="clearfix">
                                <span>{{ item.mediumName }}</span>
                            </div>
                            <div v-for="(timeItem, timeIndex) in item.mediumTimeList" :key="timeIndex"
                                class="text item">
                                {{ timeItem.chooseDate + ' 至 ' + timeItem.chooseEndDate }}
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 新增编辑其他项目 -->
        <el-dialog :title="formTitle" custom-class="otherDialog" :visible.sync="addMediumOtherProjectDialogVisible"
            width="50%" :before-close="addMediumOtherProjectHandleClose">
            <div>
                <el-form :model="addMediumOtherProjectForm" :rules="addMediumOtherProjectRules"
                    ref="addMediumOtherProjectForm" label-position="right" label-width="80px">
                    <el-form-item label="项目名称" prop="projectName" :label-width="formLabelWidth">
                        <el-input v-model="addMediumOtherProjectForm.projectName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="类型" prop="otherProjectType" :label-width="formLabelWidth">
                        <el-select v-model="addMediumOtherProjectForm.otherProjectType" placeholder="请选择">
                            <el-option v-for="(item, index) in otherProjectTypeList" :key="index"
                                :label="item.sysValueName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="品牌" prop="brands" :label-width="formLabelWidth">
                        <el-input v-model="addMediumOtherProjectForm.brands" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                        <el-input v-model="addMediumOtherProjectForm.remark" type="textarea"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addMediumOtherProjectHandleClose">取 消</el-button>
                <el-button type="primary" @click="addMediumOtherProjectSubmit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 选择导出的时间段 -->
        <el-dialog :title="formTitle" custom-class="otherDialog" :visible.sync="exportChooseTimeDialogVisible"
            width="50%" :before-close="exportChooseTimeHandleClose">
            <div>
                <el-form :model="exportChooseTimeForm" label-position="right" label-width="80px">
                    <el-form-item label="日期类型" prop="dateType" :label-width="formLabelWidth" v-if="exportType == 1">
                        <el-radio-group v-model="exportChooseTimeForm.dateType">
                            <el-radio :label="1">月份</el-radio>
                            <el-radio :label="2">年</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="起始-月" prop="startMonth" :label-width="formLabelWidth"
                        v-if="exportChooseTimeForm.dateType === 1">
                        <el-date-picker v-model="exportChooseTimeForm.startMonth" clearable type="month"
                            placeholder="选择起始月">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束-月" prop="endMonth" :label-width="formLabelWidth"
                        v-if="exportChooseTimeForm.dateType === 1">
                        <el-date-picker v-model="exportChooseTimeForm.endMonth" clearable type="month"
                            :picker-options="pickerOptions" placeholder="选择结束月">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="年份" prop="chooseYear" :label-width="formLabelWidth"
                        v-if="exportChooseTimeForm.dateType === 2">
                        <el-date-picker v-model="exportChooseTimeForm.chooseYear" clearable type="year"
                            placeholder="选择年份">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="exportChooseTimeHandleClose">取 消</el-button>
                <el-button type="primary" :loading="exportLoading" @click="handleExportTableSureTime">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import APIProject from "@/api/apiProject";
import APIMediumOtherProject from "@/api/apiMediumOtherProject";
import APISysLabel from "@/api/apiSysLabel";
import Calendar from "@/components/calendar/Calendar3";
export default {
    name: "MediumDateShow",
    components: {
        Calendar,
    },
    props: {
        operationList: Array,
    },
    data() {
        return {
            tokenData: {
                token: localStorage.getItem("mujingtoken")
            },
            dateCalendarDialog: false,
            dataPackageOfflineList: [],
            calendarStartTime: new Date().getTime(),
            calendarEndTime: new Date().getTime(),
            calendarType: 1,
            calendarScrollLeftStatus: true,
            destroyCloseDateCalendarDialog: false,
            projectChooseMap: {},
            chooseAllProjectList: [],
            chooseMediumOtherProjectList: [],
            chooseAllProjectShowList: [],
            chooseMediumOtherProjectShowList: [],
            chooseAllProjectIdList: [],
            chooseMediumOtherProjectIdList: [],
            chooseProjectTitle: '选择项目',
            tableLoading: false,
            dataList: [],
            pageSize: 10,
            pageNum: 1,
            total: 0,
            pageSizes: [10, 20, 50, 100],
            chooseMediumOtherProjectDialogVisible: false,
            chooseProjectType: 3,
            searchForm: {
                keyword: "",
                projectType: null,
            },
            projectTypeList: [],
            projectPackageList: [],
            projectPackageDrawer: false,
            projectPackageDrawerTitle: '',
            showLoading: false,
            otherProjectTypeList: [],
            addMediumOtherProjectDialogVisible: false,
            addMediumOtherProjectForm: {
                id: null,
                projectName: '',
                otherProjectType: null,
                brands: '',
                remark: '',
            },
            addMediumOtherProjectRules: {
                projectName: { required: true, message: '请输入项目名称', trigger: 'blur' },
                otherProjectType: { required: true, message: '请选择类型', trigger: 'change' },
                brands: { required: true, message: '请输入品牌', trigger: 'blur' },
            },
            formTitle: '新增其他项目',
            formLabelWidth: '120px',
            showButtonType: 1, // 1、查询、排期，2、取消查询，3、取消排期
            beforeShowButtonType: 1,
            chooseShowButtonType: 1,
            projectPackageShow: false,
            chooseProjectMsg: {},
            calendarChooseTime: null,
            sureTypeShow: false,
            sureType: 2,
            exportChooseTimeDialogVisible: false,
            exportChooseTimeForm: {
                dateType: 1,
                startMonth: null,
                endMonth: null,
                chooseYear: null,
            },
            exportStartTime: null,
            exportEndTime: null,
            pickerOptions: {},
            exportType: 1,
            exportLoading: false,
            showCleanDateType: 1, // 2为清楚dateList
            endDayNum: 7,
            projectId:null,
            choosemouth:'',
            ischoosemouth:false,
            islocalTime: localStorage.getItem('choosedmouth') || null, // 从本地存储中获取缓存时间
        };
    },
    watch: {
        "exportChooseTimeForm.startMonth"(newDate, oldDate) {
            this.pickerOptions = {
                disabledDate(time) {
                    let timeyear = time.getFullYear();
                    let timemonth = time.getMonth() + 1;
                    if (timemonth >= 1 && timemonth <= 9) {
                        timemonth = "0" + timemonth;
                    }
                    const elTimeDate = timeyear.toString() + timemonth.toString();
                    if (newDate) {
                        let newDateyear = new Date(newDate).getFullYear();
                        let newDatemonth = new Date(newDate).getMonth() + 1;
                        if (newDatemonth >= 1 && newDatemonth <= 9) {
                            newDatemonth = "0" + newDatemonth;
                        }
                        const newDateTimeDate = newDateyear.toString() + newDatemonth.toString();
                        return elTimeDate < newDateTimeDate
                    }
                }
            }
        }
    },
    activated() {
        this.showLoading = false
        this.showPackage(1);
    },
    created() { },
    methods: {
        // 导出统计
        handleExportCount() {
            if (!this.exportChooseTimeForm) {
                this.$message.error('请选择时间')
                return;
            }
            const params = {
                token: this.$store.state.token,
                startTime: new Date(this.getStartDayByMonth(this.calendarStartTime)).getTime(),
                endTime: new Date(this.getEndDayByMonth(this.calendarEndTime)).getTime(),
            };
            params.startTime = new Date(this.getStartDayByYear(this.exportChooseTimeForm.chooseYear)).getTime()
            params.endTime = new Date(this.getEndDayByYear(this.exportChooseTimeForm.chooseYear)).getTime()
            APIMediumOtherProject.doExportMediumDateCount(params).then((res) => {
                this.exportLoading = false
                if (res) {
                    const content = res.data;
                    const blob = new Blob([content]);
                    // 从response的headers中获取filename,
                    // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
                    var contentDisposition = res.headers["content-disposition"];
                    var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
                    var result = patt.exec(contentDisposition);
                    const fileName = decodeURI(result[1]);
                    if ("download" in document.createElement("a")) {
                        // 非IE下载
                        const elink = document.createElement("a");
                        elink.download = fileName;
                        elink.style.display = "none";
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href); // 释放URL 对象
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, fileName);
                    }
                }
            });
        },
        handleExportTableSureTime(){
            this.exportLoading = true
            if (this.exportType == 2){
                this.handleExportCount()
            } else {
                this.handleExportTable()
            }
        },
        exportChooseTimeHandleClose(){
            this.exportChooseTimeDialogVisible = false
        },
        handleExportTableShow(val){
            this.formTitle = "导出日期"
            this.exportChooseTimeDialogVisible = true
            this.exportChooseTimeForm = {
                dateType: val ? val : 1,
                startMonth: this.calendarStartTime,
                endMonth: this.calendarEndTime,
                chooseYear: this.calendarStartTime,
            }
            this.exportType = val
            this.exportLoading = false
        },
        getStartDayByYear(chooseDate) {
            var d = new Date(chooseDate);
            var year = d.getFullYear();
            var month = d.getMonth() + 1;
            var date = d.getDate();
            var newdate = new Date(year, 0, 1);
            return newdate.getTime();
        },
        getEndDayByYear(chooseDate){
            var d = new Date(chooseDate);
            var year = d.getFullYear();
            var month = d.getMonth() + 1;
            var date = d.getDate();
            var newdate = new Date(year, 11, 31);
            return newdate.getTime();
        },
        getStartDayByMonth(chooseDate) {
            var d = new Date(chooseDate);
            var year = d.getFullYear();
            var month = d.getMonth();
            var date = d.getDate();
            var newdate = new Date(year, month, 1);
            return newdate.getTime();
        },
        getEndDayByMonth(chooseDate) {
            var d = new Date(chooseDate);
            var year = d.getFullYear();
            var month = d.getMonth();
            var date = d.getDate();
            var lastDayOfMonth = new Date(new Date().setMonth(month + 1, 0)).getDate();
            var newdate = new Date(year, month, lastDayOfMonth);
            return newdate.getTime();
        },
        handleExportTable() {
            if(!this.exportChooseTimeForm){
                this.$message.error('请选择时间')
                return;
            }
            if (new Date(this.exportChooseTimeForm.endMonth).getTime() < new Date(this.exportChooseTimeForm.startMonth).getTime()) {
                this.$message.error('结束月份不能小于开始月份')
                return;
            }
            const params = {
                token: this.$store.state.token,
                startTime: new Date(this.getStartDayByMonth(this.calendarStartTime)).getTime(),
                endTime: new Date(this.getEndDayByMonth(this.calendarEndTime)).getTime(),
            };
            if (this.exportChooseTimeForm.dateType === 1){
                params.startTime = new Date(this.getStartDayByMonth(this.exportChooseTimeForm.startMonth)).getTime()
                params.endTime = new Date(this.getEndDayByMonth(this.exportChooseTimeForm.endMonth)).getTime()
            }else if (this.exportChooseTimeForm.dateType === 2){
                params.startTime = new Date(this.getStartDayByYear(this.exportChooseTimeForm.chooseYear)).getTime()
                params.endTime = new Date(this.getEndDayByYear(this.exportChooseTimeForm.chooseYear)).getTime()
            }
            APIMediumOtherProject.doExportMediumDate(params).then((res) => {
                this.exportLoading = false
                if (res) {
                    const content = res.data;
                    const blob = new Blob([content]);
                    // 从response的headers中获取filename,
                    // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
                    var contentDisposition = res.headers["content-disposition"];
                    var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
                    var result = patt.exec(contentDisposition);
                    const fileName = decodeURI(result[1]);
                    if ("download" in document.createElement("a")) {
                        // 非IE下载
                        const elink = document.createElement("a");
                        elink.download = fileName;
                        elink.style.display = "none";
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href); // 释放URL 对象
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, fileName);
                    }
                }
            });
        },
        changeShowButton(type){
            this.beforeShowButtonType = JSON.parse(JSON.stringify(this.showButtonType))
            this.showButtonType = type;
            this.chooseShowButtonType = type;
            this.projectId = null;
            if(type == 1){
                this.projectPackageDrawer = false
                this.sureTypeShow = false
                this.clearProjectPackage()
            } else if (type == 2) {
                this.chooseAllProject()
                this.showButtonType = 1
            } else if (type == 3) {
                this.chooseAllProject()
                this.showButtonType = 1
            }
        },
        addMediumOtherProjectSubmit() {
            this.$refs['addMediumOtherProjectForm'].validate((valid) => {
                if (valid) {
                    this.$bus.$emit("show-loading", true);
                    const params = this.addMediumOtherProjectForm;
                    APIMediumOtherProject.doAddMediumOtherProject(params).then((res) => {
                        if (res.key === 1000) {
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            this.addMediumOtherProjectDialogVisible = false;
                        }
                        this.$bus.$emit("show-loading", false);
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addMediumOtherProjectHandleClose(){
            this.addMediumOtherProjectDialogVisible = false;
        },
        addOtherMediumProject() {
            this.formTitle = "新增其他项目";
            this.getSysLabel()
            this.addMediumOtherProjectForm = {
                id: null,
                projectName: '',
                otherProjectType: null,
                brands: '',
                remark: '',
            };
            this.addMediumOtherProjectDialogVisible = true;
        },
        getSysLabel() {
            this.$bus.$emit("show-loading", true);
            const params = {
                token: this.$store.state.token,
                sysLabelIds: '43',
            };
            APISysLabel.getSysLabelValueManageList(params).then((res) => {
                if (res.key === 1000) {
                    this.otherProjectTypeList = res.result.data[43];
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        clearProjectPackage(type) {
            this.chooseAllProjectShowList = []
            this.chooseAllProjectList = []
            this.chooseAllProjectIdList = []
            this.showPackage(1);
        },
        handleCloseProjectPackageDrawer() {
            this.projectPackageDrawer = false
        },
        doDelChooseProject(index, type) {
            this.$bus.$emit("show-loading", true);
            this.chooseAllProjectShowList.splice(index, 1)
            this.chooseAllProjectList.splice(index, 1)
            this.chooseAllProjectIdList.splice(index, 1)
            this.showPackage(1);
        },
        getOneProjectPackageListMsg(projectId, type, brands) {
            this.$bus.$emit("show-loading", true);
            this.projectPackageDrawerTitle = brands
            const params = {
                token: this.$store.state.token,
                projectId: projectId,
                lineType: type
            };
            APIProject.getOneProjectPackageList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result.list;
                    res.forEach(item => {
                        if (item.createTime) {
                            item.createDate = this.$moment(item.createTime).format("YYYY-MM-DD HH:mm");
                        }
                        if (item.mediumTimeList && item.mediumTimeList.length > 0) {
                            item.mediumTimeList.forEach(timeItem => {
                                if (timeItem.chooseTime) {
                                    timeItem.chooseDate = this.$moment(timeItem.chooseTime).format("YYYY-MM-DD");
                                }
                                if (timeItem.chooseEndTime) {
                                    timeItem.chooseEndDate = this.$moment(timeItem.chooseEndTime).format("YYYY-MM-DD");
                                }
                            })
                        }
                    })
                    this.projectPackageDrawer = true
                    this.projectPackageList = res
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        commitChooseMediumProject() {
            this.showButtonType = this.chooseShowButtonType
            this.chooseMediumOtherProjectDialogVisible = false
            this.chooseAllProjectShowList = JSON.parse(JSON.stringify(this.chooseAllProjectList))
            this.chooseMediumOtherProjectShowList = JSON.parse(JSON.stringify(this.chooseMediumOtherProjectList))
            //this.showPackage(1)
            let item = this.chooseAllProjectList[0]
            this.chooseProjectMsg = item
            this.sureType = 2
            this.sureTypeShow = true
            this.projectId = item.id
            if (this.showButtonType != 3) {
                this.getOneProjectPackageListMsg(item.id, item.projectType == 1 ? 2 : 3, item.brands)
            }
        },
        handleCurrentChangeRow(list, item) {
            let key = item.projectType + "-" + item.id
            if (this.chooseAllProjectIdList && this.chooseAllProjectIdList.length > 0) {
                this.$refs.multipleProjectTable.clearSelection();
                this.$refs.multipleProjectTable.toggleRowSelection(item);
                this.chooseAllProjectIdList = []
                this.chooseAllProjectList = []
                if (!this.chooseAllProjectIdList.includes(key)) {
                    this.chooseAllProjectIdList.push(key)
                    this.chooseAllProjectList.push(item)
                } else {
                    let index = this.chooseAllProjectIdList.indexOf(key)
                    this.chooseAllProjectIdList.splice(index, 1)
                    this.chooseAllProjectList.splice(index, 1)
                }
            } else {
                this.chooseAllProjectIdList.push(key)
                this.chooseAllProjectList.push(item)
            }
        },
        handleCurrentChangeRowAll(val) {
            if (val && val.length > 0) {
                val.forEach(item => {
                    let key = item.projectType + "-" + item.id
                    if (this.chooseAllProjectIdList && this.chooseAllProjectIdList.length > 0) {
                        if (!this.chooseAllProjectIdList.includes(key)) {
                            this.chooseAllProjectIdList.push(key)
                            this.chooseAllProjectList.push(item)
                        }
                    } else {
                        this.chooseAllProjectIdList.push(key)
                        this.chooseAllProjectList.push(item)
                    }
                })
            } else {
                this.dataList.forEach(item => {
                    let key = item.projectType + "-" + item.id
                    if (this.chooseAllProjectIdList && this.chooseAllProjectIdList.length > 0) {
                        if (this.chooseAllProjectIdList.includes(key)) {
                            let index = this.chooseAllProjectIdList.indexOf(key)
                            this.chooseAllProjectIdList.splice(index, 1)
                            this.chooseAllProjectList.splice(index, 1)
                        }
                    }
                })
            }
        },
        handleCurrentChangeTable(val) {
        },
        // 分页pageSize改变
        handleSizeChange(e) {
            this.pageSize = e;
            this.reProjectPosts();
        },
        // 分页pageNum改变
        handleCurrentChange(e) {
            this.pageNum = e;
            this.getAllProject()
        },
        // 重新请求
        reProjectPosts() {
            this.pageNum = 1;
            this.dataList = [];
            this.getAllProject()
        },

        formatDate() {
    if (this.islocalTime) {
        const [year, month] = this.islocalTime.split('-');
        const date = new Date(year, parseInt(month) - 1);
        const options = { year: 'numeric', month: 'long' };
        return this.$moment(this.islocalTime).format("YYYY-MM");;
    }
    return '选择月份';
},
        getAllProject() {
            this.$bus.$emit("show-loading", true);
            const params = {
                token: this.$store.state.token,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            };
            if (this.searchForm.keyword) {
                params.keyword = this.searchForm.keyword;
            }
            if (this.searchForm.projectType) {
                params.projectType = this.searchForm.projectType;
            }
            APIMediumOtherProject.getAllProjectByYiHuoAndMedium(params).then((res) => {
                if (res.key === 1000) {
                    this.total = res.result.count;
                    res = res.result.list;
                    res.forEach(item => {
                        if (item.createTime) {
                            item.createDate = this.$moment(item.createTime).format("YYYY-MM-DD HH:mm");
                        }
                    })
                    this.dataList = res;
                    this.$nextTick(() => {
                        if (this.chooseAllProjectIdList && this.chooseAllProjectIdList.length > 0) {
                            this.dataList.forEach(dataItem => {
                                this.chooseAllProjectIdList.forEach(item => {
                                    let a = item.split("-")
                                    if (a[1] == dataItem.id && a[0] == dataItem.projectType) {
                                        this.$refs.multipleProjectTable.toggleRowSelection(dataItem);
                                    }
                                })
                            })
                        }
                    })
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        getMediumOtherProjectPost() {
            this.$bus.$emit("show-loading", true);
            const params = {
                token: this.$store.state.token,
                pageNum: this.pageNum,
                pageSize: this.pageSize
            };
            if (this.searchForm.keyword) {
                params.keyword = this.searchForm.keyword;
            }
            if (this.searchForm.projectType) {
                params.projectType = this.searchForm.projectType;
            }
            APIMediumOtherProject.getMediumOtherProjectList(params).then((res) => {
                if (res.key === 1000) {
                    this.total = res.result.count;
                    res = res.result.list;
                    res.forEach(item => {
                        if (item.createTime) {
                            item.createDate = this.$moment(item.createTime).format("YYYY-MM-DD HH:mm");
                        }
                    })
                    this.dataList = res;
                    this.$nextTick(() => {
                        if (this.chooseMediumOtherProjectIdList && this.chooseMediumOtherProjectIdList.length > 0) {
                            this.dataList.forEach(dataItem => {
                                this.chooseMediumOtherProjectIdList.forEach(item => {
                                    if (item == dataItem.id) {
                                        this.$refs.multipleProjectTable.toggleRowSelection(dataItem);
                                    }
                                })
                            })
                        }
                    })
                }
                this.$bus.$emit("show-loading", false);
            });
        },
        chooseAllProject() {
            this.chooseProjectType = 2
            this.chooseProjectTitle = '选择项目'
            this.searchForm = {
                keyword: "",
                projectType: null,
            }
            this.pageNum = 1;
            this.dataList = [];
            this.getAllProject();
            this.chooseMediumOtherProjectDialogVisible = true;
        },
        // 选择其他项目弹窗
        chooseMediumOtherProject() {
            this.chooseProjectType = 3
            this.chooseProjectTitle = '选择其他项目'
            this.searchForm = {
                keyword: "",
                projectType: null,
            }
            this.pageNum = 1;
            this.dataList = [];
            this.getMediumOtherProjectPost();
            this.chooseMediumOtherProjectDialogVisible = true;
        },
        chooseMediumOtherProjectHandleClose() {
            this.chooseMediumOtherProjectDialogVisible = false;
        },

        formatterTime(time) {
            const timestamp = parseInt(time, 10);
            const currentDate = new Date(timestamp);
            return this.$moment(currentDate).format("YYYY-MM");
        },
        closeDateCalendarDialog() {
            this.calendarStartTime = new Date().getTime()
            this.calendarEndTime = this.calendarStartTime
            this.dataPackageOfflineList = []
            this.calendarScrollLeftStatus = true
            this.calendarType = 1;
        },
        scrollStartCalendar(val) {
            this.calendarChooseTime = val.dateTime
            return
            // 日历滑到最左边了
            this.getLastMonthStart(new Date(val.dateTime))
            this.getLastMonthEnd(new Date(val.dateTime))
            this.$nextTick(() => {
                this.showPackage(2)
            })
        },
        scrollStartCalendar2(val) {
            // 点击后查看上个月
            this.getLastMonthStart(new Date(this.calendarChooseTime),1)
            this.getLastMonthEnd(new Date(this.calendarChooseTime))
            this.$nextTick(() => {
                this.showPackage(2)
                this.calendarChooseTime = null
            })
        },
        getLastMonthStart(currentDate,num) {
            // 获取上个月的第一天
              // 如果传了数字说明点击了上个月 将月份减1  
            let chooosedmouth = localStorage.getItem('choosedmouth');
            if(chooosedmouth && num != 1){
                const timestamp = parseInt(chooosedmouth, 10);
                currentDate = new Date(timestamp);
            }
            if(num == 1){
                currentDate.setMonth(currentDate.getMonth() - 1);
            }else{
                currentDate.setMonth(currentDate.getMonth());
            }
            // 将日期设置为1        
            currentDate.setDate(1);
            // 获取上个月的第一天
            let firstDayOfLastMonth = new Date(currentDate.getTime());
            this.calendarStartTime = firstDayOfLastMonth.getTime();

            //         if (!currentDate) {
            //     currentDate = new Date();
            // }
            // // 将日期设置为1
            // currentDate.setDate(1);
            // // 将时间设置为00:00:00
            // currentDate.setHours(0, 0, 0, 0);
            // // 获取指定月份的第一天
            // let firstDayOfMonth = new Date(currentDate.getTime());
            // this.calendarStartTime = firstDayOfMonth.getTime();
        },
        getLastMonthEnd(currentDate) {
            // 获取上个月的最后一天
            // 将月份减1
            let chooosedmouth = localStorage.getItem('choosedmouth');
            if(chooosedmouth){
                currentDate.setMonth(currentDate.getMonth() + 3);
            }else{
                currentDate.setMonth(currentDate.getMonth());
            }
         
            currentDate.setDate(0);
            currentDate.setHours(23, 59, 59, 999);
            let firstDayOfLastMonth = new Date(currentDate.getTime());
            this.calendarEndTime = firstDayOfLastMonth.getTime();
        },
        scrollEndCalendar(val) {
            // 日历滑到最右边了
            this.getNextMonthStart(new Date(val.dateTime))
            this.getNextMonthEnd(new Date(val.dateTime))
            this.$nextTick(() => {
                this.showPackage(2)
            })
        },
        getNextMonthStart(currentDate) {
            // 获取下个月的第一天
            // 将月份加1
            currentDate.setMonth(currentDate.getMonth() + 1);
            // 将日期设置为1
            currentDate.setDate(0);
            currentDate.setHours(0, 0, 0, 0);
            // 获取下个月的第一天
            let firstDayOfNextMonth = new Date(currentDate.getTime());
            firstDayOfNextMonth.setDate(1);
            this.calendarStartTime = firstDayOfNextMonth.getTime();
        },
        getNextMonthEnd(currentDate) {
            // // 获取下个月的最后一天
            //      // 根据 calendarStartTime 创建日期对象
            // let startDate = new Date(this.calendarStartTime);
            // // 将月份加2
            // startDate.setMonth(startDate.getMonth() + 3);
            // // 将日期设置为下个月的第0天，即当前月的最后一天
            // startDate.setDate(0);
            // // 将时间设置为23:59:59.999
            // startDate.setHours(23, 59, 59, 999);
            // this.calendarEndTime = startDate.getTime();
            let lastDayOfNextMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 2, 0, 23, 59, 59, 999)
            this.calendarEndTime = lastDayOfNextMonth.getTime();
        },
        showPackage(type) {
            this.calendarScrollLeftStatus = false;
            this.$bus.$emit("show-loading", true);
            if (this.showLoading){
                return
            }
            this.showLoading = true
            if (type == 1) {
                var currentDate = new Date()
                let chooosedmouth = localStorage.getItem('choosedmouth');
                if (chooosedmouth) {
                    const timestamp = parseInt(chooosedmouth, 10);
                    currentDate = new Date(timestamp);
                }
                this.getLastMonthStart(currentDate)
                this.getNextMonthEnd(currentDate)
                this.dataPackageOfflineList = []
                this.projectChooseMap = {}
                this.calendarType = this.calendarType + 1;
            }
            if (type == 2) {
                this.showCleanDateType = -1;
            }
            let that = this;
            let params = {
                startTime: this.calendarStartTime,
                endTime: this.calendarEndTime,
            }
            if (this.chooseAllProjectIdList && this.chooseAllProjectIdList.length > 0 && this.showButtonType != 3) {
                params.showChooseProjectType = 1
                let chooseYihuoProjectIdList = []
                let chooseMediumOtherProjectIdList = []
                this.chooseAllProjectIdList.forEach(item => {
                    let a = item.split("-")
                    if(a[0] == 1){
                        chooseYihuoProjectIdList.push(a[1])
                    } else {
                        chooseMediumOtherProjectIdList.push(a[1])
                    }
                })
                if (chooseYihuoProjectIdList && chooseYihuoProjectIdList.length > 0) {
                    params.chooseYihuoProjectIds = chooseYihuoProjectIdList.join(",")
                }
                if (chooseMediumOtherProjectIdList && chooseMediumOtherProjectIdList.length > 0) {
                    params.chooseMediumOtherProjectIds = chooseMediumOtherProjectIdList.join(",")
                }
            }
            APIProject.viewOfflineHasPackageProjectList(params).then((res) => {
                if (res.key === 1000) {
                    let result = res.result
                    let list = result.list
                    let qList = []
                    let projectChooseMap = this.projectChooseMap
                    list.forEach(item => {
                        if (item.projectMsgDTOList && item.projectMsgDTOList.length > 0) {
                            item.projectMsgDTOList.forEach(projectItem => {
                                if (projectItem && projectItem.id && projectItem.chooseTime) {
                                    projectItem.date = this.$moment(projectItem.chooseTime).format("yyyy-MM-DD")
                                    if (projectChooseMap[item.id + '-' + this.$moment(projectItem.chooseTime).format("YYYY-MM-DD")]) {
                                        let hasJoin = false;
                                        projectChooseMap[item.id + '-' + this.$moment(projectItem.chooseTime).format("YYYY-MM-DD")].forEach(aItem => {
                                            if (aItem.id == projectItem.id) {
                                                hasJoin = true
                                            }
                                        })
                                        if (!hasJoin) {
                                            projectChooseMap[item.id + '-' + this.$moment(projectItem.chooseTime).format("YYYY-MM-DD")].push(projectItem)
                                        }
                                    } else {
                                        projectChooseMap[item.id + '-' + this.$moment(projectItem.chooseTime).format("YYYY-MM-DD")] = [projectItem]
                                    }
                                }
                            })
                        }
                    })
                    this.projectChooseMap = projectChooseMap
                    var indexNum = 0;
                    list.forEach(item => {
                        // 处理原本 num 的循环
                        for (let i = 0; i < item.num; i++) {
                            item.rank = i;
                            item.areaType = 1;
                            indexNum = indexNum + 1;
                            item.indexNum = indexNum
                            qList.push(JSON.parse(JSON.stringify(item)));
                        }
                        // 处理额外的 lineUpNum 的循环，并添加标记
                        for (let i = 0; i < item.lineUpNum; i++) {
                            item.rank = i; // 继续递增 rank 为 item.rank + i
                            item.areaType = 2;
                            indexNum = indexNum + 1;
                            item.indexNum = indexNum
                            const newItem = JSON.parse(JSON.stringify(item));
                            newItem.isExtra = true; // 添加标记
                            qList.push(newItem);
                        }
                    });

                    qList.forEach(item => {
                        item.projectMsgDTOList = item.projectList
                    })
                    let offlineList = []
                    qList.forEach(item => {
                        let dto = item
                        dto.chooseNum = item.num
                        // 永远也执行不到的语句
                        // if (dto.projectMsgDTOList && dto.projectMsgDTOList.length > 0) {
                        //     let projectMap = {}
                        //     dto.projectChooseList = dto.projectMsgDTOList
                        //     dto.projectMsgDTOList.forEach(projectItem => {
                        //         if (projectItem && projectItem.chooseTime) {
                        //             projectItem.date = this.$moment(projectItem.chooseTime).format("YYYY-MM-DD");
                        //             let a = projectMap[projectItem.date];
                        //             if (a) {
                        //                 a.push(projectItem.projectName);
                        //             } else {
                        //                 projectMap[projectItem.date] = [projectItem.projectName];
                        //             }
                        //         }
                        //     })
                        //     dto.projectMap = projectMap;
                        // }
                        offlineList.push(dto)
                    })
                    let dtoList = []
                    dtoList = offlineList
                    let showOfflineList = [
                        {
                            name: ''
                        },
                    ]
                    let showList = showOfflineList.concat(dtoList)
                    that.dataPackageOfflineList = JSON.parse(JSON.stringify(showList))
                    this.calendarType = this.calendarType + 1;
                    if (type == 1) {
                        that.dateCalendarDialog = true
                    }
                    this.showCleanDateType = this.showCleanDateType + 1
                    this.$bus.$emit("show-loading", false);
                    this.showLoading = false
                }
            });
        },

        //选择月份
        handchoosemouth(){
            this.ischoosemouth = true;
        },

        changemouth(e){
            this.choosemouth = e
        },

        surehandclick(){
            if(this.choosemouth){
                const [year, month] = this.choosemouth.split('-').map(Number);
                const date = new Date(year, month - 1, 1);
                //  // 存入localStorage
                localStorage.setItem('choosedmouth', date.getTime().toString());
                this.calendarChooseTime = date.getTime();
                this.islocalTime =  this.calendarChooseTime;
                this.getLastMonthStart(new Date(this.calendarChooseTime))
                this.getLastMonthEnd(new Date(this.calendarChooseTime))
                this.$nextTick(() => {
                    this.showPackage(2)
                    this.calendarChooseTime = null
                })
                this.showCleanDateType = 10;
                this.ischoosemouth = false;
            }
        }
    },
};
</script>

<style>
.device-list {
    padding: 20px 0;
    position: relative;
}

.el-button-group {
    display: inline-flex;
}

.choose_project_list {
    /* padding-left: 20px;
    margin-bottom: 20px;
    margin-top: -20px; */
    margin: -25px 0 0 20px;
}

.project_item {
    /* display: inline-block; */
    margin: 5px 0;
}

.project_item_content {
    padding-top: 5px;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
}

.project_item_content_list {
    padding-left: 10px;
    display: flex;
    padding-bottom: 5px;
}

.project_item_content_item {}

.package_drawer {
    margin: 5px 20px;
    padding-top: 60px;
}

.package_drawer_item {
    padding-bottom: 10px;
}
.show_package{
    width: 20%;
    position: fixed;
    top: 120px;
    right: 10px;
    height: 500px;
    background-color: white;
    border-radius: 2%;
    box-shadow: 1px 1px 4px 1px;
    z-index: 999;
}
.package_header{
    margin: 10px auto;
    text-align: center;
}
.package_divider{
    display: block;
    height: 1px;
    width: 100%;
    margin: 10px 0;
    background-color: #DCDFE6;
}
.package_header_close{
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
}
.package_msg{
    width: 100%;
    height: 100%;
}
.package_title{
    position: absolute;
    width: 100%;
    background-color: white;
}
.package_content{
    height: 100%;
    overflow-x: auto;
}

.primary-color{
    color: #0b57d0;
    cursor: pointer;
}

.colorbiaoshi{
    display: flex;
    position: absolute;
    right: 1%;
    top: 1%;
    flex-direction: column;
    align-items: flex-start;
}

.colorbox{
   width: 30px;
   height: 20px;
   margin-right: 5px;
}

.color1{
    background-color: lightgoldenrodyellow;
}
.color2{
    background-color: lightgray;
}
.color3{
    background-color: lightgreen;
}


</style>
<style lang="scss" scoped>
    ::v-deep .all-select .cell .el-checkbox__inner {
        display: none;
    }
</style>
<style lang="sass">
</style>
